window.onload = function () {
    document.getElementById("communication-drafts").className = "add_class";
    document.getElementById("correspondence").className = "add-nav-active";
    // inbox_initialize();

};


function inbox_initialize(page=1,query_type='',query_value='') {
    document.getElementById("loading").style.display='inline-block';
    var xhr = new XMLHttpRequest();
    var local_host = window.location.host;          // 获取当前IP
    xhr.open('post', "/correspondence/sent.html", true);
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                document.getElementById("loading").style.display = "none";
                var JsonDate = JSON.parse(xhr.responseText);
                window.JSONdetail = JsonDate["data"]["user_li"];
                window.page = page;
                create_table(JsonDate["data"]["total_count"], JsonDate["data"]["inbox_li"]);
                pagenum(JsonDate["data"]["total_count"], page,query_type,query_value);
            }
        }
    };
}

// 动态创建列表
function create_table(count_num, json_data) {
    var t_table = document.getElementById("t_table");
    deltr();
    if (json_data.length === 0){
        document.getElementById("img-display").style.display = "inline-block";
    }else {
        document.getElementById("img-display").style.display = "none";
    }
    for (var i=0; i<json_data.length; i++) {
        var tr = document.createElement("tr");
        var td = document.createElement("td");var td1 = document.createElement("td");var td2 = document.createElement("td");var td3 = document.createElement("td");
        td.innerHTML = "<input id='"+json_data[i]["id"]+"' class='check_box' type=\"checkbox\">";td.style.background="#f8f9fa";td.style.textAlign = "center";
        td1.innerHTML = json_data[i]["recipient_name"];td1.title = json_data[i]["recipient_name"];td1.style.textAlign = "center";
        td2.innerHTML = '<a href="edit-draft?message_id='+json_data[i]["message_id"]+'" onclick="RenderInboxDetail('+i+')" id="'+i+'" style="margin-left: 1%;" target="_blank">'+json_data[i]["title"]+'</a>';td2.title = json_data[i]["title"];td2.className='username';
        td3.innerHTML = json_data[i]["create_time"];td3.title = json_data[i]["create_time"];td3.style.textAlign = "center";

        tr.appendChild(td);tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);
        t_table.appendChild(tr);
    }
    document.getElementById("loading").style.display='none';
}

// 删除列表
function deltr(){
    var tb = document.getElementById('t_table');
    var rowNum=tb.rows.length;
    for (i=0;i<rowNum;i++) {
        tb.deleteRow(i);
        rowNum=rowNum-1;
        i=i-1;
    }
}

// 加载分页条
function pagenum(dataTotals=0, page=1,query_type,query_value) {
    new myPagination({
        id: 'pagination',
        curPage: page, //初始页码
        pageAmount: 20,  //每页多少条
        dataTotal: dataTotals, //总共多少条数据
        pageTotal:  Math.ceil(parseInt(dataTotals, 10)/20), //总页数
        pageSize: 5, //可选,分页个数
        showPageTotalFlag:true, //是否显示数据统计
        showSkipInputFlag:true, //是否支持跳转
        getPage: function (page) {
            var query_type = document.getElementById("query_type").value;
            var query_value = document.getElementById("query_value").value;
            inbox_initialize(page,query_type,query_value);
            document.getElementById("check_all").checked = false;
        }
    });
}

// 全选与反全选
function check_all_not() {
    var check_box_list = document.getElementsByClassName("check_box");
    if (document.getElementById("check_all").checked) {
        for (var t=0; t<check_box_list.length; t++) {
            check_box_list[t].checked = true;
        }
    }else {
        for (var j=0; j<check_box_list.length; j++) {
            check_box_list[j].checked = false;
        }
    }
}

// 确认删除
function ConfirmDelete() {
    var myArray = new Array();
    var check_box_list = document.getElementsByClassName("check_box");
    var tb_list = document.getElementsByClassName("username");
    for (var t=0; t<check_box_list.length; t++) {
        if (check_box_list[t].checked) {
            console.log(check_box_list[t])
            console.log(tb_list[t])
            myArray.push(check_box_list[t].id)
        }
    }
    if (myArray.length === 0){
        document.getElementById("Confirm-content").innerHTML = "没有选择删除的用户！";
    }else {
        document.getElementById("Confirm-content").innerHTML = "确认要删除这"+String(myArray.length)+"个用户吗？"
    }
}

// 批量删除数据
function DeleteData() {
    var myArray = []
    var check_box_list = document.getElementsByClassName("check_box");
    var tb_list = document.getElementsByClassName("username");
    for (var t=0; t<check_box_list.length; t++) {
        if (check_box_list[t].checked) {
            myArray.push(tb_list[t].title)
        }
    }
    if (myArray.length === 0){
        document.getElementById("close-model2").click();
        return myArray
    }
    var xhr = new XMLHttpRequest();
    var local_host = window.location.host;          // 获取当前IP
    xhr.open('post', "/system-setup/user-message", true);
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xhr.send("delete_list="+String(myArray)+"&page=1");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                document.getElementById("close-model2").click();
                initialize();
            }
        }
    };
}


function send_message() {
    document.getElementById("loading").style.display='inline-block';
    var form = new FormData();
    var recipient = document.getElementById("recipient").value;
    var title = document.getElementById("title").value;
    var message_content = editor.txt.html().replaceAll("&", "%26");

    var tr_tag = document.getElementById("t_table");
    var file_list = new Array();
    for(var i=0 ;i<tr_tag.rows.length;i++) {
        var file_dict = {};
        file_dict["file_name"] = tr_tag.rows[i].cells[1].innerHTML;
        file_dict["file_path"] = tr_tag.rows[i].cells[5].children[0].href;
        file_dict["file_size"] = tr_tag.rows[i].cells[2].innerHTML;
        file_dict["upload_time"] = tr_tag.rows[i].cells[3].innerHTML;
        file_dict["upload_people"] = tr_tag.rows[i].cells[4].innerHTML;
        file_dict["pdf_path"] = tr_tag.rows[i].cells[5].children[2].href;
        file_list.push(file_dict);
        console.log(file_list);
    }

    var message_id = document.getElementById("message_id").innerHTML;

    var xhr=new XMLHttpRequest();
    var local_host = window.location.host;
    xhr.open('post', "/correspondence/send-message", true);
    form.append('recipient', String(recipient));
    form.append('title', String(title));
    form.append('message_content', String(message_content));
    form.append('file', JSON.stringify(file_list));
    form.append('is_draft', "Ture");
    form.append('message_id', message_id);


    xhr.send(form);
    xhr.onreadystatechange=function(){
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                document.getElementById("loading").style.display='none';
                var JsonDate = JSON.parse(xhr.responseText);
                if (JsonDate["code"] === 200){
                    alert("发送成功！");
                    window.location.href='sent.html';
                }
                else {
                    alert(JsonDate["message"])
                }
            }
        }
    }
}

function edit_draft() {
    document.getElementById("loading").style.display='inline-block';
    var form = new FormData();
    var recipient = document.getElementById("recipient").value;
    var title = document.getElementById("title").value;
    var message_content = editor.txt.html().replaceAll("&", "%26");
    var tr_tag = document.getElementById("t_table");
    var file_list = new Array();

    for(var i=0 ;i<tr_tag.rows.length;i++) {
        var file_dict = {};
        file_dict["file_name"] = tr_tag.rows[i].cells[1].innerHTML;
        file_dict["file_path"] = tr_tag.rows[i].cells[5].children[0].href;
        file_dict["file_size"] = tr_tag.rows[i].cells[2].innerHTML;
        file_dict["upload_time"] = tr_tag.rows[i].cells[3].innerHTML;
        file_dict["upload_people"] = tr_tag.rows[i].cells[4].innerHTML;
        file_dict["pdf_path"] = tr_tag.rows[i].cells[5].children[2].href;
        file_list.push(file_dict);
    }

    var message_id = document.getElementById("message_id").innerHTML;

    var xhr=new XMLHttpRequest();
    var local_host = window.location.host;
    xhr.open('post', "/correspondence/edit-draft", true);
    form.append('recipient', String(recipient));
    form.append('title', String(title));
    form.append('message_content', String(message_content));
    form.append('message_id', String(message_id));
    form.append('is_draft', String(1));
    form.append('file', JSON.stringify(file_list));

    xhr.send(form);
    xhr.onreadystatechange=function(){
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                document.getElementById("loading").style.display='none';
                var JsonDate = JSON.parse(xhr.responseText);
                if (JsonDate["code"] === 200){
                    alert("保存成功！");
                    window.location.href='drafts.html';
                }
                else {
                    alert(JsonDate["message"])
                }
            }
        }
    }
}

